package test302;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class Http302 {

	private static String userId = "60989480242c3e8a";
	private static String downloadPath = "D:\\测试";

	/**
	 * 
	 * @param urlPath
	 *            下载路径
	 * @param urlFileName
	 *            下载文件名
	 * @param downloadDir
	 *            下载存放目录
	 */
	public static void downloadFile(String urlPath, String urlFileName, String downloadDir) {
		File file = null;

		try {
			// 统一资源
			URL url = new URL(urlPath);
			// 连接类的父类，抽象类
			URLConnection urlConnection = url.openConnection();
			// http的连接类
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			// 设定请求的方法，默认是GET
			httpURLConnection.setRequestMethod("GET");
			// 设置字符编码
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			// 打开到此 URL 引用的资源的通信链接（如果尚未建立这样的连接）。
			httpURLConnection.connect();

			// 文件大小
			String fileSize = fileSizeConver(httpURLConnection.getContentLength());

			// 文件名
			String fileFullName = urlFileName + ".m4a";

			System.out.println("文件大小:" + fileSize);

			BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

			String path = downloadDir + File.separatorChar + fileFullName;
			System.out.println("存储路径:" + path);
			file = new File(path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			OutputStream out = new FileOutputStream(file);
			int size = 0;
			byte[] buf = new byte[1024];
			// bin.skip(18);
			// 如果是jsonp格式，需要跳过开始的callback函数名和一个左括号

			while ((size = bin.read(buf)) != -1) {
				/*
				 * if(size<1024) { size=size-1; } //如果是jsonp格式，还需去掉最后一个右括号
				 */
				out.write(buf, 0, size);
			}

			bin.close();
			out.close();
			System.out.println("下载完成!");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param fileS
	 *            文件的字节数
	 * @return fileSizeString 文件大小的字符串
	 */
	public static String fileSizeConver(long fileS) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		String wrongSize = "0B";
		if (fileS == 0) {
			return wrongSize;
		}
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "MB";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "GB";
		}
		return fileSizeString;
	}

	public static void main(String[] args) {
		try {
			int moreFlag = 0; // 是否还有下一页
			int index = 1;
			do {
				String url = "http://node.kg.qq.com/cgi/fcgi-bin/kg_ugc_get_homepage?outCharset=utf-8&format=json&type=get_uinfo&start="
						+ index + "&num=8&share_uid=" + userId;
				URL serverUrl = new URL(url);
				HttpURLConnection con = (HttpURLConnection) serverUrl.openConnection();

				con.setRequestMethod("GET");
				con.addRequestProperty("Accept-Charset", "UTF-8;");
				con.addRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");

				int responseCode = con.getResponseCode();
				System.out.println("\nSending 'GET' request to URL : " + url);
				System.out.println("Response Code : " + responseCode);

				BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
				String inputLine;
				StringBuffer response = new StringBuffer();

				while ((inputLine = in.readLine()) != null) {
					response.append(inputLine);
				}
				in.close();

				// 打印获取到的json格式result
				System.out.println(response.toString());

				// json数据解析
				JSONObject jsonObject = JSON.parseObject(response.toString());
				System.out.println(jsonObject.getString("data"));

				JSONObject jsonDataObject = JSON.parseObject(jsonObject.getString("data"));
				System.out.println(jsonDataObject.getString("has_more"));

				// 获取是否还有下一页，修改moreFlag值
				moreFlag = Integer.parseInt(jsonDataObject.getString("has_more"));
				index++;

				// ugclist是Array类型，将其转换成JSONArray类型
				JSONArray recordMap = (JSONArray) jsonDataObject.get("ugclist");
				System.out.println("数量:" + recordMap.size());

				// 测试获取第一组数据的shareid和title
				String shareid = recordMap.getJSONObject(0).getString("shareid");
				String title = recordMap.getJSONObject(0).getString("title");
				System.out.println(shareid + " " + title);

				for (int i = 0; i < recordMap.size(); i++) {
					String urlTemp = "http://node.kg.qq.com/cgi/fcgi-bin/fcg_get_play_url?shareid="
							+ recordMap.getJSONObject(i).getString("shareid");
					// System.out.println("访问地址:" + urlTemp);
					URL serverUrlTemp = new URL(urlTemp);
					HttpURLConnection conn = (HttpURLConnection) serverUrlTemp.openConnection();
					conn.setRequestMethod("GET");
					// 获取302请求的location地址，必须设置false，否则会自动redirect到Location的地址
					conn.setInstanceFollowRedirects(false);

					conn.addRequestProperty("Accept-Charset", "UTF-8;");
					conn.addRequestProperty("User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");

					String location = conn.getHeaderField("Location");
					// System.out.println("跳转地址:" + location);

					// 设置下载文件名
					String fileTitle = recordMap.getJSONObject(i).getString("title");
					// 下载文件
					downloadFile(location, fileTitle, downloadPath);
				}
			} while (moreFlag == 1);// do-while

			System.out.println("\n@@@全部下载完成!!!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
